from Unit import Unit
from operator import attrgetter
from collections import namedtuple


unit_obj = Unit()
unit_list = unit_obj.getUnitList()['con']
# print(unit_list)
# [{'parent_id': '1100469', 'unit_id': '1722555', 'unit_name': '氢能装备机械研发', 'unit_rank': 100000},...]

node_dict = {}

for unit_obj in unit_list:
    # 定义一个namedtuple类型Unit_tuple，并包含相应parent_id等属性
    Unit_tuple = namedtuple('Unit_tuple', ['parent_id', 'unit_id', 'unit_name'])
    unit_tuple = Unit_tuple(parent_id=unit_obj.get('parent_id'), unit_id=unit_obj['unit_id'], unit_name=unit_obj['unit_name'])
    node_dict[unit_tuple.unit_id] = unit_tuple
    # node_list.append(unit_tuple)
print(node_dict)
# {'1722555': Unit_tuple(parent_id='1100469', unit_id='1722555', unit_name='氢能装备机械研发'), ...
# '2988761_default': Unit_tuple(parent_id=None, unit_id='2988761_default', unit_name='默认部门')}

def traversal(node_dict, unit_id):
    if node_dict[unit_id].parent_id is None:
        return [node_dict[unit_id]]
    else:
        return traversal(node_dict, node_dict[unit_id].parent_id) + [node_dict[unit_id]]

def funcA(unit_id):
    for i_dict in unit_list:
        if not i_dict.get('parent_id') and i_dict.get('unit_id') == unit_id:
            return i_dict.get('unit_name')

for i in node_dict.keys():
    res = traversal(node_dict, i)
    path = ','.join(map(attrgetter('unit_id'), res))
    print(funcA(path.split(',')[0])+'+'+node_dict[i].unit_name, path.split(',')[0]+'+'+path.split(',')[-1])





# # 先寻找一级部门
# def query_PriOrg(node_list):
#     primaryOrg_list = []
#     for tmp_node in node_list:
#         PriUnit_tuple = namedtuple('PriUnit_tuple', ['unit_id', 'unit_name'])
#         if 'parent_id' not in tmp_node._fields:
#             priUnit_tuple = PriUnit_tuple._make([tmp_node.unit_id, tmp_node.unit_name])
#             primaryOrg_list.append(priUnit_tuple)
#     return primaryOrg_list
#
# primaryOrg_list = query_PriOrg(node_list)
# print(primaryOrg_list)
#
# # 获取一级部门ID
# a_list = []
# for a in primaryOrg_list:
#     a_list.append(a.unit_id)
# print(a_list)
# #
# # # 获取非一级部门ID
# # b_list = []
# # for a in primaryOrg_list:
# #     a_list.append(a.unit_id)
# # print(a_list)
#
#
# def funcA(unit_id):
#     for f in node_list:
#         # 如果此节点的id在所有节点的父节点中
#         try:
#             f.parent_id
#         except:
#             continue
#         else:
#             if unit_id == f.parent_id:
#                 return None
#     return unit_id
#
# list_a = []
# for a in node_list:
#     b = funcA(a.unit_id)
#     if b:
#         list_a.append(b)
#
# print(list_a)
#
# def funcB(Unit_tuple, list_b):
#     dict = {}
#     if Unit_tuple.parent_id in a_list:
#         dict['parent_id'] = Unit_tuple.parent_id
#         dict['unit_id'] = Unit_tuple.unit_id
#         list_b.append(dict)
#     else:
#         funcB(Unit_tuple.parent_id)
#
# list_b = {}
# for f in node_list:
#     funcB(f, list_b)